import React from "react";
import {Modal, Row, Card, Spin, Table, Select, Input, Col} from "antd";
import {openNotificationWithIcon} from "utils/comm";
import { connect } from "dva";


class SkipList extends React.Component {

  columns = [
    {
      title: "节点编码",
      dataIndex: "id",
      render: (v) => this.getEllipsisCell(v, 79),
    },
    {
      title: "节点名称",
      dataIndex: "name",
      render: (v) => this.getEllipsisCell(v, 100),
    },
    {
      title: "操作",
      dataIndex: "opration",
      render: (text, record) => {
        return (
          <div>
            <a onClick={(e) => {
              e.preventDefault();
              this.Skip(record);
            }}
            >
              强制跳转
            </a>
          </div>
        );
      },
    },
  ];

  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon;
    this.state = {
      currentActivity: [],
      newActivity: [],
      selectedCurrentActivity: {},
      skipVariable: [],
      flowParamList: {},
    };
  }


  componentDidMount() {
    this.getSkipList();
  }

  getEllipsisCell = (v, maxWidth) => {
    return (
      <span
        style={{
          display: "inline-block",
          maxWidth,
        }}
        title={v}
      >
        {v}
      </span>
    );
  }

  getSkipList = () => {
    const { dispatch, processInstanceId } = this.props;
    if (!dispatch) return;
    dispatch({
      type: "FlowMonitor/getTaskSkipList",
      payload: {processInstanceId},
    }).then(({ errCode, datas }) => {
      if (errCode !== 0) {
        this.openNotificationWithIcon("error", "", "获取流程节点信息失败");
      }
      this.setState({ newActivity: datas.newActivity, currentActivity: datas.currentActivity, selectedCurrentActivity:datas.currentActivity?.[0] });
    });
  };

  Skip = (record) => {
    const { selectedCurrentActivity, flowParamList } = this.state;
    const { dispatch, processInstanceId } = this.props;
    const params = { processInstanceId, currentActivityId:selectedCurrentActivity.id,
      taskId:selectedCurrentActivity.taskId, newActivityId: record.id, comment:"强制跳转", flowParamList };
    dispatch({
      type: "FlowMonitor/getTaskSkip",
      payload: params,
    }).then(({datas, errCode, errMsg }) => {

      if (errCode === 0) {
        this.handleCancel();
        // eslint-disable-next-line react/destructuring-assignment
        this.props.initData();
        this.openNotificationWithIcon("success", "", "操作成功");
      } else if (errCode === 902020) {
          // 需要设置变量
          this.setState({skipVariable : datas})
      } else {
          this.openNotificationWithIcon("warning", "", errMsg || "操作失败");
      }
    });
  };

  handleCancel = () => {
    const {handleSkipCancel} = this.props;
    handleSkipCancel(false);
    this.setState({ newActivity: [], currentActivity: [], selectedCurrentActivity: {}, skipVariable:[], flowParamList: {} });
  };

  currentActivityChange = (record) => {
    const { currentActivity } = this.state;
    if (Array.isArray(currentActivity)){
      const selected = currentActivity.filter((item) => item.taskId === record);
      if (Array.isArray(selected)){
        this.setState({ selectedCurrentActivity: selected[0]})
      }
    }
  }

  skipVariableChange = (value, code) => {
    const { flowParamList } = this.state;
    flowParamList[code] = value
    this.setState({flowParamList: {...flowParamList}});
  }

  render() {
    const { Option } = Select;
    const { visible } = this.props;
    const { newActivity, currentActivity, skipVariable } = this.state;

    const {
      loading: { effects },
      title = '流程节点列表',
    } = this.props;
    const rootLoading = effects["FlowMonitor/getTaskSkipList"] || false;
    let defaultValue;
    if (Array.isArray(currentActivity)){
      defaultValue = currentActivity[0]?.taskId;
    }
    return (
      <Modal
        title={title}
        visible={visible}
        // onOk={this.handleOk}
        onCancel={this.handleCancel}
        footer={null}
        width="800px"
      >
        <Row style={{ paddingBottom: 20 }}>
          <Col span={12}>
            当前节点
            <Select
              showSearch
              placeholder="选择需要跳转的节点"
              onChange={this.currentActivityChange}
              style={{ width: 200, marginLeft: 10 }}
              defaultValue={defaultValue}
              key={defaultValue}
              optionLabelProp="label"
            >
              {Array.isArray(currentActivity) && currentActivity.map((item) => (
                <Option value={item.taskId} label={item.name} title={item.taskId}>
                  {`${item.name} (任务ID：${item.taskId})`}
                </Option>
              ))}
            </Select>
          </Col>
          {Array.isArray(skipVariable) && skipVariable.length > 0 && (
            <Col span="12">
              变量赋值
              {skipVariable.map((item) => (
                <Input
                  key={item.code}
                  placeholder={`请输入变量${item.name}的值`}
                  style={{ width: 200, marginLeft: 10 }}
                  onChange={v => this.skipVariableChange(v.target.value, item.code)}
                />
              ))}
            </Col>
          )}
        </Row>
        <Row style={{ height: 352 }}>

          <Card
            size="small"
            bodyStyle={{ height: 323, overflow: "auto" }}
          >
            <Spin spinning={rootLoading}>
              <div>
                <Table
                  rowKey="id"
                  columns={this.columns}
                  dataSource={newActivity}
                />
              </div>
            </Spin>
          </Card>

        </Row>

      </Modal>
    );
  }
}
const ConnectTreeStore = (Component) => connect(({ loading }) => ({
  loading,
}))(Component);

export default ConnectTreeStore(SkipList);
